<template>
  <el-dialog v-model="state.dialogVisible" :title="state.dialogTitle" width="800px">
    <el-form :model="state.form" :rules="state.rules" ref="formRef" label-width="120px">
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="订单信息" prop="orderInfo">
            <el-descriptions :column="2" border>
              <el-descriptions-item label="订单号">{{ state.form.orderCode }}</el-descriptions-item>
              <el-descriptions-item label="商品名称">{{ state.form.goodsName }}</el-descriptions-item>
              <el-descriptions-item label="数量">{{ state.form.quantity }}</el-descriptions-item>
              <el-descriptions-item label="当前状态">{{ state.form.currentStatus }}</el-descriptions-item>
            </el-descriptions>
          </el-form-item>
        </el-col>
        
        <el-col :span="12">
          <el-form-item label="调出仓库" prop="fromWarehouseId">
            <el-select v-model="state.form.fromWarehouseId" placeholder="请选择调出仓库" clearable filterable @change="onFromWarehouseChange">
              <el-option 
                v-for="warehouse in state.warehouseList" 
                :key="warehouse.id" 
                :label="warehouse.name" 
                :value="warehouse.id" 
              />
            </el-select>
          </el-form-item>
        </el-col>
        
        <el-col :span="12">
          <el-form-item label="调出库位" prop="fromLocationId">
            <el-select v-model="state.form.fromLocationId" placeholder="请选择调出库位" clearable filterable :disabled="!state.form.fromWarehouseId">
              <el-option 
                v-for="location in state.fromLocationList" 
                :key="location.id" 
                :label="location.name" 
                :value="location.id" 
              />
            </el-select>
          </el-form-item>
        </el-col>
        
        <el-col :span="12">
          <el-form-item label="调入仓库" prop="toWarehouseId">
            <el-select v-model="state.form.toWarehouseId" placeholder="请选择调入仓库" clearable filterable @change="onToWarehouseChange">
              <el-option 
                v-for="warehouse in state.warehouseList" 
                :key="warehouse.id" 
                :label="warehouse.name" 
                :value="warehouse.id" 
              />
            </el-select>
          </el-form-item>
        </el-col>
        
        <el-col :span="12">
          <el-form-item label="调入库位" prop="toLocationId">
            <el-select v-model="state.form.toLocationId" placeholder="请选择调入库位" clearable filterable :disabled="!state.form.toWarehouseId">
              <el-option 
                v-for="location in state.toLocationList" 
                :key="location.id" 
                :label="location.name" 
                :value="location.id" 
              />
            </el-select>
          </el-form-item>
        </el-col>
        
        <el-col :span="12">
          <el-form-item label="调拨数量" prop="transferQuantity">
            <el-input-number 
              v-model="state.form.transferQuantity" 
              :min="1" 
              :max="Math.max(state.form.quantity, 1)" 
              placeholder="请输入调拨数量"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        
        <el-col :span="12">
          <el-form-item label="调拨类型" prop="transferType">
            <el-select v-model="state.form.transferType" placeholder="请选择调拨类型" clearable>
              <el-option label="仓库间调拨" value="warehouse" />
              <el-option label="库位间调拨" value="location" />
              <el-option label="部门间调拨" value="department" />
              <el-option label="其他调拨" value="other" />
            </el-select>
          </el-form-item>
        </el-col>
        
        <el-col :span="12">
          <el-form-item label="调拨金额" prop="transferAmount">
            <el-input-number 
              v-model="state.form.transferAmount" 
              :min="0" 
              :precision="2"
              placeholder="请输入调拨金额"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        
        <el-col :span="12">
          <el-form-item label="调拨原因" prop="transferReason">
            <el-select v-model="state.form.transferReason" placeholder="请选择调拨原因" clearable>
              <el-option label="库存调整" value="inventory_adjustment" />
              <el-option label="销售需要" value="sales_need" />
              <el-option label="库存优化" value="inventory_optimization" />
              <el-option label="其他原因" value="other" />
            </el-select>
          </el-form-item>
        </el-col>
        
        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input 
              v-model="state.form.remark" 
              type="textarea" 
              :rows="3" 
              placeholder="请输入备注信息"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleConfirm" :loading="state.loading">确认调拨</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup name="transferDialog">
import { ref, reactive, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { useSysinstockorderApi } from '/@/api/OutWarehou/sysinstockorder';
import { useSysoutstockorderApi } from '/@/api/OutWarehou/sysoutstockorder';
import { useWarehouseModelApi } from '/@/api/interacting/warehouse/warehouseModel';
import { useWarePlaceModelApi } from '/@/api/interacting/warehouse/warePlaceModel';

const emit = defineEmits(['confirm', 'cancel']);

const instockApi = useSysinstockorderApi();
const outstockApi = useSysoutstockorderApi();
const warehouseApi = useWarehouseModelApi();
const warePlaceApi = useWarePlaceModelApi();
const formRef = ref();
const state = reactive({
  dialogVisible: false,
  dialogTitle: '调拨操作',
  loading: false,
  warehouseList: [] as any[],
  fromLocationList: [] as any[],
  toLocationList: [] as any[],
  form: {
    orderId: null,
    orderCode: '',
    goodsName: '',
    quantity: 0,
    currentStatus: '',
    fromWarehouseId: null,
    fromLocationId: null,
    toWarehouseId: null,
    toLocationId: null,
    transferQuantity: 0,
    transferType: 'warehouse',
    transferAmount: 0,
    transferReason: 'inventory_adjustment',
    remark: ''
  },
  rules: {
    fromWarehouseId: [
      { required: true, message: '请选择调出仓库', trigger: 'change' }
    ],
    fromLocationId: [
      { required: true, message: '请选择调出库位', trigger: 'change' }
    ],
    toWarehouseId: [
      { required: true, message: '请选择调入仓库', trigger: 'change' }
    ],
    toLocationId: [
      { required: true, message: '请选择调入库位', trigger: 'change' }
    ],
    transferQuantity: [
      { required: true, message: '请输入调拨数量', trigger: 'blur' },
      { type: 'number', min: 1, message: '调拨数量必须大于0', trigger: 'blur' }
    ],
    transferType: [
      { required: true, message: '请选择调拨类型', trigger: 'change' }
    ],
    transferReason: [
      { required: true, message: '请选择调拨原因', trigger: 'change' }
    ]
  }
});

// 打开对话框
const openDialog = (orderData: any) => {
  state.dialogVisible = true;
  state.form = {
    orderId: orderData.id,
    orderCode: orderData.code,
    goodsName: orderData.goodsName,
    quantity: orderData.transferQuantity || orderData.quantity || orderData.itemQuantity || orderData.salesQuantity || orderData.returnQuantity || orderData.salesReturnQuantity || 0,
    currentStatus: orderData.documentStatus,
    fromWarehouseId: null,
    fromLocationId: null,
    toWarehouseId: null,
    toLocationId: null,
    transferQuantity: orderData.transferQuantity || orderData.quantity || orderData.itemQuantity || orderData.salesQuantity || orderData.returnQuantity || orderData.salesReturnQuantity || 0,
    transferType: 'warehouse',
    transferAmount: 0,
    transferReason: 'inventory_adjustment',
    remark: ''
  };
  
  loadWarehouseList();
};

// 加载仓库列表
const loadWarehouseList = async () => {
  try {
    const res = await warehouseApi.page({
      page: 1,
      pageSize: 1000, // 获取所有仓库
      wareType: true // 只获取启用的仓库
    });
    
    // 转换数据格式
    state.warehouseList = (res.data?.result?.items || res.data?.result || []).map((warehouse: any) => ({
      id: warehouse.id,
      name: warehouse.wareName,
      code: warehouse.wareCode,
      address: warehouse.wareAddr
    }));
  } catch (error) {
    console.error('加载仓库列表失败:', error);
    ElMessage.error('加载仓库列表失败');
    // 如果API调用失败，使用空数组
    state.warehouseList = [];
  }
};

// 调出仓库变化时加载库位列表
const onFromWarehouseChange = async (warehouseId: any) => {
  state.form.fromLocationId = null;
  state.fromLocationList = [];
  
  if (!warehouseId) return;
  
  try {
    const res = await warePlaceApi.page({
      page: 1,
      pageSize: 1000, // 获取所有库位
      warehouseId: warehouseId, // 按仓库ID筛选库位
      warePlaceType: true // 只获取启用的库位
    });
    
    // 转换数据格式
    state.fromLocationList = (res.data?.result?.items || res.data?.result || []).map((location: any) => ({
      id: location.id,
      name: location.warePlaceName,
      code: location.warePlaceCode,
      volume: location.warePlaceVolume
    }));
  } catch (error) {
    console.error('加载调出库位列表失败:', error);
    ElMessage.error('加载调出库位列表失败');
    // 如果API调用失败，使用空数组
    state.fromLocationList = [];
  }
};

// 调入仓库变化时加载库位列表
const onToWarehouseChange = async (warehouseId: any) => {
  state.form.toLocationId = null;
  state.toLocationList = [];
  
  if (!warehouseId) return;
  
  try {
    const res = await warePlaceApi.page({
      page: 1,
      pageSize: 1000, // 获取所有库位
      warehouseId: warehouseId, // 按仓库ID筛选库位
      warePlaceType: true // 只获取启用的库位
    });
    
    // 转换数据格式
    state.toLocationList = (res.data?.result?.items || res.data?.result || []).map((location: any) => ({
      id: location.id,
      name: location.warePlaceName,
      code: location.warePlaceCode,
      volume: location.warePlaceVolume
    }));
  } catch (error) {
    console.error('加载调入库位列表失败:', error);
    ElMessage.error('加载调入库位列表失败');
    // 如果API调用失败，使用空数组
    state.toLocationList = [];
  }
};

// 确认调拨
const handleConfirm = async () => {
  if (!formRef.value) return;
  
  try {
    await formRef.value.validate();
    state.loading = true;
    
    // 生成出库单号（调出）
    const outstockCode = `CKDH${Date.now()}`;
    // 生成入库单号（调入）
    const instockCode = `RKDH${Date.now() + 1}`;
    
    // 获取仓库名称
    const fromWarehouse = state.warehouseList.find(w => w.id === state.form.fromWarehouseId);
    const toWarehouse = state.warehouseList.find(w => w.id === state.form.toWarehouseId);
    const fromWarehouseName = fromWarehouse?.name || '未知仓库';
    const toWarehouseName = toWarehouse?.name || '未知仓库';
    
    // 获取调拨类型中文名称
    const transferTypeMap: { [key: string]: string } = {
      'warehouse': '仓库间调拨',
      'location': '库位间调拨',
      'department': '部门间调拨',
      'other': '其他调拨'
    };
    const transferTypeName = transferTypeMap[state.form.transferType] || '仓库间调拨';
    
    // 获取调拨原因中文名称
    const transferReasonMap: { [key: string]: string } = {
      'inventory_adjustment': '库存调整',
      'sales_need': '销售需要',
      'inventory_optimization': '库存优化',
      'other': '其他原因'
    };
    const transferReasonName = transferReasonMap[state.form.transferReason] || '库存调整';
    
    // 先创建出库单（调出）
    await outstockApi.add({
      code: outstockCode,
      outType: transferTypeName,
      documentStatus: 6, // 已完成状态
      outDate: new Date().toISOString().split('T')[0],
      warehouseName: fromWarehouseName,
      relatedCode: state.form.orderCode,
      goodsName: state.form.goodsName,
      agentName: '系统操作员', // 可以从用户信息获取
      outQuantity: state.form.transferQuantity,
      warehouseAmount: state.form.transferAmount || 0,
      remark: state.form.remark || `调拨出库，来源于订单：${state.form.orderCode}，调拨原因：${transferReasonName}`
    });
    
    // 再创建入库单（调入）
    await instockApi.add({
      code: instockCode,
      inType: transferTypeName,
      documentStatus: 6, // 已完成状态
      inDate: new Date().toISOString().split('T')[0],
      warehouseName: toWarehouseName,
      relatedCode: state.form.orderCode,
      goodsName: state.form.goodsName,
      agentName: '系统操作员', // 可以从用户信息获取
      inQuantity: state.form.transferQuantity,
      warehouseAmount: state.form.transferAmount || 0,
      remark: state.form.remark || `调拨入库，来源于订单：${state.form.orderCode}，调拨原因：${transferReasonName}`
    });
    
    ElMessage.success('调拨操作成功，已生成出库单和入库单');
    emit('confirm', {
      ...state.form,
      outstockCode: outstockCode,
      instockCode: instockCode
    });
    handleClose();
  } catch (error) {
    console.error('调拨操作失败:', error);
    ElMessage.error('调拨操作失败：' + (error.message || '未知错误'));
    // 即使操作失败，也要关闭弹窗
    handleClose();
  } finally {
    state.loading = false;
  }
};

// 关闭对话框
const handleClose = () => {
  state.dialogVisible = false;
  state.form = {
    orderId: null,
    orderCode: '',
    goodsName: '',
    quantity: 0,
    currentStatus: '',
    fromWarehouseId: null,
    fromLocationId: null,
    toWarehouseId: null,
    toLocationId: null,
    transferQuantity: 0,
    transferType: 'warehouse',
    transferAmount: 0,
    transferReason: 'inventory_adjustment',
    remark: ''
  };
  emit('cancel');
};

defineExpose({
  openDialog
});
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}
</style>
